<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="userLoading"
      :data="users"
      border
      fit
      row-key="id"
      default-expand-all
      style="width: 100%;"
    >
      <el-table-column
        type="index"
        width="50"
        align="center"
        sortable="custom"
      />
      <el-table-column label="成员" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickname || row.username.split('@')[0] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属部门" align="center">
        <template slot-scope="{row}">
          <span>{{ (row.organization && row.organization.name) || '暂无归属' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center">
        <template slot-scope="{row}">
          <span>{{ row.job || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职级" align="center">
        <template slot-scope="{row}">
          <span>L{{ row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行政级别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.rank | rankFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.user_type | commonTypeFilter">{{ row.user_type | userTypeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="'500px'">
      <el-form ref="dataForm" :rules="dialogStatus === 'create' ? createRules : updateRules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:40px;">
        <el-form-item label="用户昵称" :prop="dialogStatus === 'create' ? 'nickname' : ''">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="邮箱账号" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item v-show="dialogStatus === 'create'" label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item v-show="dialogStatus === 'create'" label="确认密码" prop="password_confirm">
          <el-input v-model="temp.password_confirm" />
        </el-form-item>
        <el-form-item label="角色" prop="user_type">
          <el-radio-group v-model="temp.user_type">
            <el-radio :label="1">超级管理员</el-radio>
            <el-radio :label="2">管理员</el-radio>
            <el-radio :label="3">普通成员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="归属部门">
          <el-select v-model="temp.organization_id" class="filter-item" placeholder="请选择" value-key="string" @change="$forceUpdate()">
            <el-option v-for="item in organizations" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="行政级别" prop="rank">
          <el-radio-group v-model="temp.rank">
            <el-radio :label="1">总监</el-radio>
            <el-radio :label="2">经理</el-radio>
            <el-radio :label="3">职员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="岗位">
          <el-input v-model="temp.job" />
        </el-form-item>
        <el-form-item label="职级">
          <el-input-number v-model="temp.level" :min="0" :max="7" label="职级" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="dialogStatus === 'update'" type="warning" style="float:left;" @click="resetPassword">
          密码重置
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils'
import { RankMap, UserStatusMap, UserTypeMap, CommonTypeMap } from '@/utils/constant'
// import Pagination from '@/components/Pagination'
import * as OrganizationApi from '@/api/organization'
import * as UserApi from '@/api/user'

export default {
  name: 'User',
  // components: { Pagination },
  filters: {
    parseTimeFilter(time) {
      return parseTime(time)
    },
    rankFilter(item) {
      return RankMap[item]
    },
    userTypeFilter(item) {
      return UserTypeMap[item]
    },
    userStautsFilter(item) {
      return UserStatusMap[item]
    },
    commonTypeFilter(item) {
      return CommonTypeMap[item]
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      userLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 99
      },
      organizations: [],
      users: [],
      temp: {
        nickname: '',
        username: '',
        password: '',
        password_confirm: '',
        user_type: 3,
        organization_id: '',
        rank: 3,
        job: '',
        level: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '详情编辑',
        create: '新增'
      },
      createRules: {
        nickname: [{ required: true, message: '必须填写用户昵称', trigger: 'blur' }],
        username: [{ required: true, message: '必须填写邮箱账号', trigger: 'blur' }],
        password: [{ required: true, message: '必须填写密码', trigger: 'blur', min: 6, max: 18 }],
        password_confirm: [{ required: true, message: '必须填写确认密码', trigger: 'blur', min: 6, max: 18 }],
        user_type: [{ required: true, message: '必须填写用户类型', trigger: 'blur' }],
        rank: [{ required: true, message: '必须填写职级', trigger: 'blur' }]
      },
      updateRules: {
        username: [{ required: true, message: '必须填写邮箱账号', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'cur_user_id'
    ])
  },
  created() {
    this.getUsers()
    this.getOrganizations()
  },
  methods: {
    async getOrganizations() {
      this.organizations = []
      const { data } = await OrganizationApi.getOrganizaitons()
      if (data.total) {
        this.organizations = data.items
      }
    },
    async getUsers(pageQuery) {
      if (pageQuery) {
        this.listQuery = Object.assign(this.listQuery, pageQuery)
      }
      this.users = []
      this.userLoading = true
      const { data } = await UserApi.getUserList(this.listQuery)
      if (data.total) {
        this.users = data.items
        this.total = data.total
      }
      this.userLoading = false
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getUsers()
    },
    resetTemp() {
      this.temp = {
        nickname: '',
        username: '',
        password: '',
        password_confirm: '',
        user_type: '',
        organization_id: '',
        rank: '',
        job: '',
        level: ''
      }
    },
    async resetPassword() {
      const { data } = await UserApi.resetPassword(this.temp.id)
      if (data) {
        await this.$notify({
          title: 'Success',
          message: '重置密码成功！',
          type: 'success',
          duration: 2000
        })
        this.dialogFormVisible = false
      }
    },
    async handleCreate() {
      await this.getOrganizations()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          const { data } = await UserApi.createUser(this.temp)
          if (data) {
            await this.getUsers()
            await this.$notify({
              title: 'Success',
              message: '新增成员成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
          }
        }
      })
    },
    async handleUpdate(row) {
      await this.getOrganizations()
      this.temp = Object.assign({}, row) // copy obj
      this.temp['organization_id'] = (row.organization && row.organization.id) || this.temp.organization_id
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const { data } = await UserApi.updateUser(tempData)
          if (data) {
            this.dialogFormVisible = false
            await this.getUsers()
            await this.$notify({
              title: 'Success',
              message: '更新成功！',
              type: 'success',
              duration: 2000
            })
          }
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data } = await UserApi.deleteUser(row.id)
        if (data) {
          await this.getUsers()
          await this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        }
      }).catch(err => {
        console.error(err)
        this.$notify({
          title: 'Fail',
          message: '已取消删除',
          type: 'error',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}
</style>
